package org.npu.controller;

import org.apache.ibatis.session.SqlSession;
import org.npu.dao.BookDao;
import org.npu.dao.MovieDao;
import org.npu.dao.MusicDao;
import org.npu.entity.Book;
import org.npu.entity.Movie;
import org.npu.entity.Music;
import org.npu.util.MyBatisUtils;

import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

public class HomepageServlet extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        resp.setContentType("text/html;charset=utf8");

        //拿到全局作用域对象
        ServletContext application = req.getServletContext();

        /*
         使用mybatis的动态代理机制，是同SqlSession.getMapper(dao接口)
         getMapper能获取dao接口对于的实现类对象。
         */
        SqlSession sqlSession = MyBatisUtils.getSqlSession();
        BookDao bookDao = sqlSession.getMapper(BookDao.class);
        MovieDao movieDao = sqlSession.getMapper(MovieDao.class);
        MusicDao musicDao = sqlSession.getMapper(MusicDao.class);

        // 拿到最新的三个对象和数量
        Movie oneMovie = movieDao.getLatest();
        Music oneMusic = musicDao.getLatest();
        Book oneBook = bookDao.getLatest();

        //存储到全局作用域对象
        application.setAttribute("oneMovie", oneMovie);
        application.setAttribute("oneMusic", oneMusic);
        application.setAttribute("oneBook", oneBook);

//        System.out.println(oneMovie.toString());
//        System.out.println(oneMusic.toString());
//        System.out.println(oneBook.toString());

        // oneBook,oneMovie,oneMusic传到homepage
        req.getRequestDispatcher("/homepage").forward(req, resp);

    }

}
